<template>
  <div id="RetrievePw">
    <div class="page page1" v-show="showPage1">
      <h1>無&emsp;夢</h1>
      <p class="message">请输入您的用户名或电子邮箱地址。您会收到一封包含重设密码指引的电子邮件。</p>      
      <p class="error_msg message" v-show="showError"></p>
      <div class="content">
        <el-form :model="userForm" ref="userForm">
          <el-form-item prop="user">
            <label class="input_title" for="user_pw">用户名或电子邮件地址</label> 
            <el-input
              name="user_pw"
              class="input-box"
              v-model="userForm.user"
              clearable
              @keyup.enter="submitUserHandler"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <el-button 
          type="primary"
          size="small"
          @click="submitUserHandler"
          :disabled="sendingEmail"
        >
          获取新密码
        </el-button>
      </div>
    
      <router-link :to="'/'">
        <el-link class="back_home" target="_blank">
          ← 返回首页
        </el-link>
      </router-link>
    </div>

    <div class="page page2" v-show="showPage2">
      <h1>無&emsp;夢</h1>
      <p class="message rp_msg">请在下方输入您的新密码。</p>
      <div class="content" v-show="showRpInput">
        <el-form :model="pwForm" ref="pwForm">
          <el-form-item prop="pw">
            <label class="input_title" for="user_pw">新密码</label> 
            <el-input
              class="input-box"
              placeholder="* 密码"
              v-model="pwForm.pw" 
              show-password
              @keyup.enter="resetPwHandler"
            >
            </el-input>
            <label class="input_title pw_tip">提示：密码长度最短为6位字符，最长为16位字符。</label>
          </el-form-item>
        </el-form>
        <el-button 
          type="primary"
          size="small"
          @click="resetPwHandler"
          :disabled="rpBtnDisable"
        >
          重置密码
        </el-button>
      </div>
    
      <router-link :to="'/'">
        <el-link class="back_home" target="_blank">
          ← 返回首页
        </el-link>
      </router-link>
    </div>

    <div class="page page3" v-show="showPage3">
      <h1>無&emsp;夢</h1>
      <p class="message login_msg"></p>
      <p class="error_msg message" v-show="showError"></p>
      <div class="content">
        <el-form :model="loginForm" ref="loginForm">
          <el-form-item prop="user">
            <label class="input_title">用户名或邮箱</label> 
            <el-input
              class="input-box"
              v-model="loginForm.user" 
              @keyup.enter="loginHandler"
            >
            </el-input>
            <label class="input_title">密码</label> 
            <el-input
              class="input-box"
              v-model="loginForm.pw" 
              show-password
              @keyup.enter="loginHandler"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <el-button 
          type="primary"
          size="small"
          @click="loginHandler"
        >
          登录
        </el-button>
      </div>
    
      <router-link :to="'/'">
        <el-link class="back_home" target="_blank">
          ← 返回首页
        </el-link>
      </router-link>
    </div>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
  name: 'RetrievePw',
  data(){
    return{
      showError: false,
      showPage1: false,
      showPage2: false,
      showPage3: false,
      rpDisable: false,
      showRpInput: true,
      rpBtnDisable: false,
      sendingEmail: false,
      action: '',
      key: '',
      login: '',
      userForm: {
        user: ''
      },
      pwForm: {
        pw: ''
      },
      loginForm: {
        user: '',
        pw: ''
      }
    }
  },
  beforeCreate(){
    // console.log("beforeCreate:", this.$route.query)
    let query = this.$route.query
    if(Object.values(query).length === 0) return
    this.action = query.action

    if(this.action === 'rp'){
      // this.$router.push({ query: {action: 'rp'} })
    }
  },
  watch: {
    '$route':'getPath'
  },
  mounted() {
    // 动画播放完移除
    let content = document.getElementsByClassName('content')[0]
    let pw_tip = document.getElementsByClassName('pw_tip')[0]
    content.addEventListener("animationend", () => {
      content.classList.remove('shake')
    })
    pw_tip.addEventListener("animationend", () => {
      pw_tip.classList.remove('shake')
    })

    this.getPath()
  },
  methods: {
    ...mapMutations(['updateUserInfo']),
    // 监听路由参数改变
    getPath(){
      this.showError = false
      let query = this.$route.query
      if(Object.values(query).length === 0) {
        this.showPage3 = false
        this.showPage2 = false
        this.showPage1 = true
        return
      }

      let rp_msg = document.getElementsByClassName('rp_msg')[0]
      let login_msg = document.getElementsByClassName('login_msg')[0]
      
      this.action = query.action
      // console.log("getPath:", this.action);
      if(this.action === 'rp'){
        let error = query.error
        if(error && error === 'invalidkey'){
          this.showPage3 = false
          this.showPage2 = false
          this.showPage1 = true
          this.showError = true
          let error_msg = document.getElementsByClassName('error_msg')[0]
          error_msg.innerHTML = `您的密码重设链接无效，请在下方请求新链接。`
        }else{
          this.showPage2 = true
          this.showPage1 = false
          this.showPage3 = false

          this.showRpInput = true
          rp_msg.innerHTML = `请在下方输入您的新密码。`

          this.key = query.key
          this.login = query.login

          this.checkKey()
        }
      }else if(this.action === 'resetpass'){
        this.showPage2 = true
        this.showPage1 = false
        this.showPage3 = false
        
        this.showRpInput = false
        rp_msg.innerHTML = `您的密码已被重置。<a class='login_text'>登录</a>`
        this.toLogin()
      }else if(this.action === 'login'){
        this.showPage3 = true
        this.showPage1 = false
        this.showPage2 = false

        let sentEmail = query.sentEmail
        if(sentEmail && sentEmail === 'true'){
          login_msg.innerHTML = `请在您的电子邮箱中检查确认链接。`
        }else{
          login_msg.innerHTML = `密码修改成功，可以登录了。`
        }
      }
    },
    // 检查key是否有效
    async checkKey(){
      let {data} = await this.$axios({
        method: 'post',
        url: '/resetpw/check',
        data: {
          key: this.key
        }
      })

      if(data.code){
        // 无效的key
        this.$router.push({ query: {action: 'rp', error: 'invalidkey'} })        
      }
    },
    // 登录
    async loginHandler(){
      let user = this.loginForm.user.trim()
      let pass = this.loginForm.pw.trim()

      let pwReg = /^[\w,.?;<>/|\\:'"!@#$%^&*()+-]{6,16}$/
      let error_msg = document.getElementsByClassName('error_msg')[0]
      let content = document.getElementsByClassName('content')[0]

      if(user === ''){
        error_msg.innerHTML = `<strong>错误</strong>：请输入用户名或电子邮件地址。`
        content.classList.add('shake')
        return
      }
      if(!pwReg.test(pass)){
        error_msg.innerHTML = `<strong>错误</strong>：密码需为6~16位字符`
        content.classList.add('shake')
        return
      }

      let {data} = await this.$axios({
        method: 'post',
        url: '/login',
        data:{
          user, pass
        }
      })

      if(data.code){
        // 登录失败提示
        return this.$message.error(data.msg)
      }

      // 登录成功提示
      this.$message.success('登录成功')

      // 修改vuex
      this.updateUserInfo(data.data)

      // 跳转至主页
      this.$router.replace('/')
    },
    // 跳转至登录界面
    toLogin(){
      let login_text = document.getElementsByClassName('login_text')[0]
      login_text.addEventListener('click', () => {
        this.$router.push({ query: {action: 'login'} })
      })
    },
    // 密码重置
    async resetPwHandler(){
      let pw = this.pwForm.pw
      let reg = /^[\w,.?;<>/|\\:'"!@#$%^&*()+-]{6,16}$/
      let pw_tip = document.getElementsByClassName('pw_tip')[0]
      if (!reg.test(pw)) {
        pw_tip.classList.add('shake')
        return
      }

      this.rpBtnDisable = true
      let {data} = await this.$axios({
        method: 'post',
        url: '/resetpw',
        data: {
          rpkey: this.key,
          user: this.login,
          pass: pw
        }
      })

      if(data.code){
        return this.$message.error(data.msg)
      }

      this.$message.success(data.msg)
      this.$router.push({ query: {action: 'resetpass'} })
    },
    // 发邮件找回密码
    async submitUserHandler(){
      let user = this.userForm.user.trim()
      let error_msg = document.getElementsByClassName('error_msg')[0]
      let content = document.getElementsByClassName('content')[0]
      if(user === ""){
        this.showError = true
        error_msg.innerHTML = `<strong>错误</strong>：请输入用户名或电子邮件地址。`
        content.classList.add('shake')
        return
      }else if(user.length < 2){
        this.showError = true
        error_msg.innerHTML = `<strong>错误</strong>：请输入正确的用户名或电子邮件地址。`
        content.classList.add('shake')
        return
      }else{
        this.showError = false
        error_msg.innerHTML = ""
      }

      if(this.sendingEmail){
        return
      }

      this.sendingEmail = true
      let {data} = await this.$axios({
        method: 'post',
        url: '/email/retrievepw',
        data: {
          user
        }
      })

      this.sendingEmail = false
      // console.log(data);
      if(data.code){
        return this.$message.error(data.msg)
      }
      // 邮件发送成功，跳转至登录界面
      this.$router.push({ query: {action: 'login', sentEmail: 'true'} })
    }
  }
}
</script>

<style lang="less" scoped>
  @pageWidth: 320px;
  #RetrievePw{
    position: relative;
    width: @pageWidth;
    margin: 0 auto;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .page{
      .message{
        border-left: 4px solid #00a0d2;
        padding: 12px;
        margin: 20px 0 20px;
        background-color: #fff;
        box-shadow: 0 1px 1px 0 rgb(0 0 0 / 10%);
        text-align: left;
      }
      .rp_msg{
        :deep(.login_text){
          color: #0073aa;
          cursor: pointer;          
          outline: 0;
          &:hover{
            color: #00a0d2;
            text-decoration: underline;
          }
        }
      }
      .error_msg{
        border-left-color: #dc3232;
      }
      .input_title{
        display: flex;
        text-align: left;
        line-height: 30px;
      }
      .pw_tip{
        line-height: 20px;
      }
      .input-box{
        margin-bottom: 10px;
      }
      .back_home{
        width: inherit;
        text-align: left;
      }
      .content{
        position: relative;
        margin: 20px 0;
        padding: 26px 24px 46px;
        font-weight: 400;
        overflow: hidden;
        background: #fff;
        border: 1px solid #ccd0d4;
        box-shadow: 0 1px 3px rgb(0 0 0 / 4%);
      }
      .back_home{
        position: absolute;
        left: 0;
        margin-left: 20px;
      }
      :deep(.el-button--primary){
        position: absolute;
        right: 0;
        margin-right: 25px;
        background: #007cba;
        border-color: #007cba;
        color: #fff;
        text-decoration: none;
        text-shadow: none;      
      }

      .shake{
        animation:shake .2s cubic-bezier(.19,.49,.38,.79) both;
        animation-iteration-count:3;
        transform:translateX(0)
      }
      @keyframes shake{
        25%{transform:translateX(-20px)}
        75%{transform:translateX(20px)}
        100%{transform:translateX(0)}
      }
    }
  }
</style>